package cn.zhaoyuening.schoolmates.web.admin;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.baidu.ueditor.ActionEnter;

import cn.zhaoyuening.schoolmates.service.FileResourceService;
import cn.zhaoyuening.schoolmates.utils.JsonUtils;
import cn.zhaoyuening.schoolmates.utils.ResponceResult;

/**
 * Created by Zhao on 2017/4/8.
 */
@RestController
@RequestMapping("admin")
public class AdminFileResourcesController {
    @Autowired
    private FileResourceService fileResourceService;

    @RequestMapping(value = "file", method = RequestMethod.POST,produces = "text/json;charset=utf8")
    public String uploadFile(@RequestParam(value = "uploadFile",required=false)MultipartFile file) throws IOException {
        if (file!=null&&file.isEmpty())
            return JsonUtils.objectToJson(ResponceResult.fail());
        String imageUrl = fileResourceService.uploadFile(file.getBytes(), file.getOriginalFilename());
        ResponceResult result = null;
        if(StringUtils.isEmpty(imageUrl)){
        	result = ResponceResult.fail();
        	
        }else{
        	result = new ResponceResult();
        	result.setMsg("ok");
        	result.setStatus(200);
        	result.setData(imageUrl);
        }
        String jsonStr = JsonUtils.objectToJson(result);        	
        return jsonStr;
    }
    //ckeditor 图片上传
    @RequestMapping(value = "editorFile", method = RequestMethod.POST,produces = "text/json;charset=utf8")
    public String uploadImage(@RequestParam(value = "uploadFile",required=false)MultipartFile upfile) throws IOException {
        if (upfile.isEmpty())
            return JsonUtils.objectToJson(ResponceResult.fail());
        String imageUrl = fileResourceService.uploadFile(upfile.getBytes(), upfile.getOriginalFilename());
        if(StringUtils.isEmpty(imageUrl)){
        	return "error|服务器端错误";
        }
        return imageUrl;
    }
    
    @RequestMapping(value = "ued/config",produces="application/json")
    public String config(HttpServletRequest request, HttpServletResponse response){
    	response.setContentType("application/json");
        String rootPath = request.getSession()
                .getServletContext().getRealPath("/");
 
        String exec = new ActionEnter(request, rootPath).exec();
        return exec;
    }
    

}
